package user

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/app/business/api/internal/repository/integral"
	"private-domain-overseas-service/app/business/api/internal/repository/user"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizintegral"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent/hzintegralwallet"
	"private-domain-overseas-service/tools/ent/hzintegralwalletrecord"
	"private-domain-overseas-service/tools/ent/hzuser"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUserInfoLogic - 用户信息
func NewUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserInfoLogic {
	return &UserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserInfoLogic) UserInfo() (resp *types.UserInfoResponse, err error) {
	usersDao := user.NewUsersDao(l.ctx, l.svcCtx)
	integralWalletDao := integral.NewIntegralWalletDao(l.ctx, l.svcCtx)
	walletRecordDao := integral.NewIntegralWalletRecordDao(l.ctx, l.svcCtx)

	// 定义百分之一初始值
	baiDecimal := decimal.NewFromInt32(100)
	// 获取用户id
	userId := common.JwtAuthUserId(l.ctx)

	// 查询用户信息
	userCond := make([]predicate.HzUser, 0)
	userCond = append(userCond, hzuser.IDEQ(int(userId)))
	userInfo, err := usersDao.GetOneUser(userCond)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询用户信息不存在：%v", err.Error()))
	}

	// 查询用户积分钱包信息
	walletCond := make([]predicate.HzIntegralWallet, 0)
	walletCond = append(walletCond, hzintegralwallet.UserIDEQ(userId))
	walletInfo, err := integralWalletDao.IntegralWalletConditionsOnly(walletCond)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询用户积分钱包失败：%v", err.Error()))
	}

	// 判断是否为新用户
	var isNewUser = constant.OldUser

	walletRecordConditions := make([]predicate.HzIntegralWalletRecord, 0)
	walletRecordConditions = append(walletRecordConditions, hzintegralwalletrecord.RecordTypeEQ(bizintegral.NewUserReward), hzintegralwalletrecord.UserIDEQ(userId))
	first, _ := walletRecordDao.WalletRecordConditionsFirst(walletRecordConditions)
	if first == nil {
		isNewUser = constant.NewUser
	}

	// 组装返回数据
	resp = &types.UserInfoResponse{
		UserId:       int64(userInfo.ID),
		Phone:        userInfo.UserPhone,
		Email:        userInfo.UserEmail,
		UserIntegral: decimal.NewFromInt(walletInfo.WalletActiveBalance).Div(baiDecimal).StringFixed(2),
		IsNewUser:    isNewUser,
	}

	return resp, nil
}
